<template>
  <view class="pageShow" :style="{ minHeight: windowHeight + 'px' }">
    <view class="list-group" v-for="(item, gindex) in listData" :key="gindex">
      <view class="list-items" @click="changeDept(item)">
        <view class="list-body space-between flex-vcenter flex-vcenter flex w-full justify-between">
          <view class="list-title flex-auto text-ellipsis overflow-hidden">
            <text :class="['list-title-text', currRoleId == item.id ? 'font-bold' : '']" :style="{
              'white-space': 'nowrap',
              color: currRoleId == item.id ? '#0078d4' : 'grey',
              'text-overflow': 'ellipsis',
              overflow: 'hidden',
            }">{{ item.txt }}</text>
          </view>
          <view class="list-arrow-right paddingR25">
            <u-icon v-if="currRoleId == item.id" name="checkbox-mark" color="#0078d4" bold></u-icon>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getRolseConfig } from "@/king-components/js/App";
import { getInfoDetails } from "@/api/login";

export default {
  data() {
    return {
      windowHeight: "",
      listData: [],
      currRole: this.$store?.getters.roleInfo,
      // 模式：switch 切换角色，select 选择角色(选择后返回)
      mode: "switch",
    };
  },
  async onLoad(options) {
    if (options.mode) this.mode = options.mode;
    if (this.mode == "select") uni.setNavigationBarTitle({ title: "选择角色" });
    await this.getRoleData();
  },
  // #ifndef VUE3
  destroyed() {
    // 取消监听
    uni.$off("login:role-select");
  },
  // #endif
  // #ifdef VUE3
  unmounted() {
    // 取消监听
    uni.$off("login:role-select");
  },
  // #endif
  created: function () {
    uni.getSystemInfo({
      success: (res) => {
        this.windowHeight = res.windowHeight;
      },
    });
  },
  // 返回监听
  onBackPress: function (options) {
    uni.$emit("home:reload");
  },
  computed: {
    currRoleId() {
      const roleId = this.currRole?.id;
      return roleId || false;
    },
  },
  methods: {
    async getRoleData() {
      try {
        const { data, success } = await getInfoDetails();
        if (data.user) {
          const { dept, roles } = data.user;
          if (Array.isArray(roles)) {
            // 过滤，只显示 APP.js 中配置的角色
            this.listData = roles
              .filter((r) => {
                const role = getRolseConfig(r.roleAlias);
                return !!role;
              })
              .map((v) => {
                return {
                  ...v,
                  txt: v.roleName,
                  id: v.id,
                };
              });
          }
        }
      } catch (error) {
        console.error(error);
      }
    },
    //功能选择的方法
    async changeDept(item) {
      // 如果是当前的，就不需要切换
      if (item.id == this.currRoleId) {
        return uni.showToast({ title: "当前角色，无需切换", icon: "none" });
      }
      try {
        uni.showLoading({
          title: this.mode == "select" ? "选择中" : "切换中",
        });

        // 如果是选择模式，返回，并传递事件
        if (this.mode == "select") {
          uni.navigateBack();
          return uni.$emit("login:role-select", { role: item });
        }

        // 切换模式 执行刷新token （此时应已登录）
        const { deptId } = this.$store.getters.currdeptInfo;
        await this.$store.dispatch("user/refreshToken", { roleId: item.id, deptId: deptId });
        // 更新数据
        // this.currDept = this.$store?.getters.currdeptInfo;
        this.currRole = this.$store?.getters.roleInfo;
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: "切换失败",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style>
.pageShow {
  width: 100%;
  height: 100%;
  padding-top: 10px;
}

.img {
  width: 100%;
  height: 300rpx;
}

.list-items {
  padding-left: 25rpx;
  background-color: #ffffff;
}

.list-body {
  padding: 25rpx 0;
  margin-left: 0rpx;
  width: 10rpx;
  display: flex;
  justify-content: space-between;
  width: auto;
}

.paddingR25 {
  padding-right: 25rpx;
}

.list-group {
  margin: 20rpx 10px;
  border-radius: 10px;
  overflow: hidden;
}
</style>
